/*
 * @lc app=leetcode.cn id=92 lang=java
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    /**
     * Accepted
    44/44 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 53.57 % of java submissions (39.2 MB)
     */
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(0, head);
        ListNode cur = head, pre = dummy, next = null, ne = null;
        int index = 1;
        while (cur != null && index <= right) {
            if (index == left - 1) {
                pre = cur;
                cur = cur.next;
                index++;
            } else if (index == left) {
                next = cur;
                ne = cur;
                cur = cur.next;
                index++;
            } else if (index > left && index < right) {
                ListNode t = cur;
                cur = cur.next;
                t.next = next;
                next = t;
                index++;
            } else if (index == right) {
                ne.next = cur.next;
                ListNode t = cur;
                t.next = next;
                next = t;
                pre.next = next;
                return dummy.next;
            } else {
                cur = cur.next;
                index++;
            }
        }
        return dummy.next;
    }
}
// @lc code=end
